import { createSlice } from "@reduxjs/toolkit";
// 导入本地存储工具函数，用于从 localStorage 读写数据
import { getData, saveData } from "../../utils/localStorage";

// 初始化用户信息的函数：从 localStorage 尝试获取 currentUser
const initUser = () => {
  const currentUser = getData("currentUser");
  if (currentUser) {
    return currentUser;
  }
  return null;
};

// 定义 slice 的初始状态
let initialState = {
  email: "",
  username: "",
  password: "",
  errors: null,
  currentUser: initUser(), // 调用 initUser 初始化 currentUser
  token: null,
};

// 创建 loginSlice，用于管理登录相关的状态和 reducer
export const loginSlice = createSlice({
  name: "login",
  initialState,
  reducers: {
    // 更新登录表单字段的 reducer
    loginFileUpdate(state, action) {
      const key = action.payload.key;
      const value = action.payload.value;
      state[key] = value;
    },
    // 处理登录提交结果的 reducer
    loginSubmit(state, action) {
      const { status, message, data } = action.payload;
      if (status == 1) {
        let currentUser = data;
        let token = data.token;
        // 将用户信息和 token 保存到 localStorage
        saveData("currentUser", currentUser);
        saveData("token", token);
        // 更新状态，重新调用 initUser 获取
        return { ...state, ...data, currentUser: initUser() };
      } else {
        // 登录失败，更新错误信息
        return { ...state, errors: message };
      }
    },
    // 卸载时重置状态的 reducer
    onUnload() {
      // 重置状态为初始状态，重新调用 initUser 初始化 currentUser
      return { ...initialState, currentUser: initUser() };
    },
    avatarUpdate(state) {
      state.currentUser = initUser();
    },
  },
});

// 导出对应的 action 创建函数，供组件中 dispatch 使用
export const { loginFileUpdate, loginSubmit, onUnload, avatarUpdate } =
  loginSlice.actions;

// 导出 slice 的 reducer，用于配置 Redux store
export default loginSlice.reducer;
